package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;

        //判断访问的资源路径是否和登录注册相关
        String[] urls = {"/login.jsp", "/imgs/","/css/","/LoginServlet","/register.jsp","/RegisterServlet","/checkCodeServlet"};

        //获取当前请求的路径
        String url = req.getRequestURL().toString();

        //循环遍历
        for (String u : urls) {
            if (url.contains(u)){
                //包含，说明是登录注册相关的资源，放行
                chain.doFilter(request, response);
                return;
            }
        }
        //1.判断session中是否有User
        Object user = req.getAttribute("user");

        //2.判断user是否为null
        if (user !=null){
            //登陆过了
            //放行
            chain.doFilter(request, response);
        }else {
            //没有登陆过
            //跳转到登陆页面
            req.setAttribute("login_msg","您尚未登陆，请登陆");
            req.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }


}
